package day03;

import com.blackhorse.domain.Account;
import com.blackhorse.domain.AccountUser;
import com.blackhorse.domain.User;
import com.blackhorse.xml.dao.AccountMapper;
import com.blackhorse.xml.dao.UserMapper;
import org.apache.ibatis.io.Resources;
import org.apache.ibatis.session.SqlSession;
import org.apache.ibatis.session.SqlSessionFactory;
import org.apache.ibatis.session.SqlSessionFactoryBuilder;
import org.junit.After;
import org.junit.Before;
import org.junit.Test;

import java.io.IOException;
import java.io.InputStream;
import java.util.List;

public class Demo2_OneToMany {
    private SqlSessionFactory sqlSessionFactory;
    private SqlSession sqlSession;
    private UserMapper userMapper;

    @Before
    public void init() {
        try {
            InputStream in = Resources.getResourceAsStream("SqlMapConfig.xml");
            SqlSessionFactoryBuilder builder = new SqlSessionFactoryBuilder();
            sqlSessionFactory = builder.build(in);
            sqlSession = sqlSessionFactory.openSession();
            userMapper = sqlSession.getMapper(UserMapper.class);
        } catch (IOException e) {
            e.printStackTrace();
        }
    }

    @After
    public void destory() {
        sqlSession.commit();
        if (sqlSession != null) {
            sqlSession.close();
        }
    }

    //查询所有用户
    @Test
    public void testFindAll() {
        List<User> users = userMapper.findAll();
        for (User user : users) {
            System.out.println(user);
        }
    }

    //查询所有用户，同时一对多关联查询账户（使用User包装Account对象方式）
    @Test
    public void testFindAllUserWithAccount() {
        List<User> users = userMapper.findAllUserWithAccount();
        //如果不显示Account则说明该用户没有账户，即user.getAccounts().size()==0
        for (User user : users) {
            System.out.println("----------------------------------------");
            System.out.println(user);
            List<Account> accounts = user.getAccounts();
            if (accounts == null || accounts.size() == 0) {
                System.out.println("\tAccount = null");
                continue;
            }
            for (Account account : accounts) {
                System.out.println("\t" + account);
            }
        }
    }
}
